from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from fb.auth.models import FacebookProfile

class FacebookAuthBackend(ModelBackend):
    
  def authenticate(self, cookie=None):
    user = None
    if cookie and cookie['uid']:
      user = self.get_user(cookie['uid'])
      if user is None:
        user = User(username=cookie['uid'])
        user.set_unusable_password()
        user.save()
        
        profile = FacebookProfile()
        profile.user = user
        profile.change_access_token(cookie['access_token'])
        profile.refresh_profile()
        profile.refresh_permissions()
      else:
        user.get_profile().change_access_token(cookie['access_token'])
    return user
  
  def get_user(self, user_id):
    try:
      return User.objects.get(username=user_id)
    except User.DoesNotExist:
      return None
      